package com.ailang.aiskand.ui

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.ailang.aiskand.adapter.AiChatAdapter
import com.ailang.aiskand.databinding.ActivityMainBinding
import com.ailang.aiskand.databinding.LayoutAichatItemBinding
import com.ailang.aiskand.model.MainModel
import com.hzjh.base.ext.frame.JHBaseActivity
import com.hzjh.base.frame.adapter.MutableAdapter
import com.hzjh.base.frame.adapter.SimpleGapItemDecor
import com.hzjh.base.utils.function.dp2px
import com.hzjh.base.utils.other.CheckUtils
import com.hzjh.base.utils.other.KeyboardUtils

class MainActivity : JHBaseActivity<ActivityMainBinding,MainModel>() {

    private val chatAdapter by lazy {
        MutableAdapter(viewModel.aiChatLiveData.value!!).apply{
            addVhDelegate{
                AiChatAdapter(LayoutAichatItemBinding.inflate(layoutInflater,it,false))
            }
        }
    }
    override fun initData() {

    }

    override fun initView() {
        viewBinding.langTitleBar.setBackBtnVisibility(View.GONE)

        val rvMsgLayoutManager = LinearLayoutManager(this)
        rvMsgLayoutManager.stackFromEnd = true //默认从底端开始显示
        viewBinding.rvData.layoutManager =rvMsgLayoutManager

        viewBinding.rvData.addItemDecoration(
            SimpleGapItemDecor(verGap = 0.dp2px())
        )
        viewBinding.rvData.adapter = chatAdapter

        viewBinding.btnSend.setOnClickListener {
            val msg = viewBinding.etInput.text.toString()
            if(CheckUtils.isEmpty(msg)){
                return@setOnClickListener
            }
            viewModel.sendToAiMsg(msg)
            viewBinding.etInput.setText("")
            KeyboardUtils.hideSoftInput(this)
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.aiChatLiveData.observe(this){
            val indexTag = chatAdapter.itemCount-1
            val endTag=1
            chatAdapter.notifyItemRangeInserted(indexTag, endTag)
        }
    }

    override fun initViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }
}